<?php

namespace App\Http\Controllers;

use App\Models\Good;

class GoodsController extends Controller
{
    public function list(){
        $map = [];
        $keyword = request('keyword');
        if($keyword){
            $map[] = ['name','like','%'.$keyword.'%'];
        }

        $map[] = ['status','=',1];

        $list = Good::where($map)->select(['id','name','cover','desc','integral'])->simplePaginate(20);
        return renderSuccess($list);
    }

    public function detail(){
        $id = request('id');
        $detail = Good::select(['id','name','images','integral','sale','stock','content'])->find($id);
        return renderSuccess($detail);
    }


    public function addCart(){
        //添加到购物车
        $user = auth()->user();
        $goods_id = request('goods_id');
        $num = request('num',1);

        $good = Good::find($goods_id);
        if(!$good){
            return renderError('商品不存在');
        }

        $cart = $user->shopcart()->where('goods_id',$goods_id)->first();
        if($cart){
            $cart->quantity += $num;
            $cart->save();
        }else{
            $cart = $user->shopcart()->insert([
                'goods_id' => $goods_id,
                'quantity' => $num,
                'user_id' => $user->id,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
        }

        return renderSuccess([], '添加成功');
    }

    public function removeCart(){
        //从购物车移除
        $user = auth()->user();
        $goods_id = request('goods_id');

        $cart = $user->shopcart()->where('goods_id',$goods_id)->first();
        if($cart){
            $cart->delete();
        }

        return renderSuccess([], '移除成功');
    }

    public function shopCartList(){
        $user = auth()->user();
        $list = $user->shopcart()
            ->with(['goods:id,name,cover,integral'])
            ->get([
                'id',
                'goods_id',
                'quantity',
                'user_id',
                'checked'
            ]);

        return renderSuccess($list);
    }
}
